import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { LogService } from './log.service';
import { Request, Response } from 'express';

@Injectable()
export class LogInterceptor implements NestInterceptor {
  constructor(private readonly logService: LogService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const response = context.switchToHttp().getResponse<Response>();
    const userInfo = request.user as any;
    const startTime = Date.now();

    return next.handle().pipe(
      tap(async (data) => {
        const logData = {
          username: userInfo?.username || 'anonymous',
          path: request.path,
          method: request.method,
          params: JSON.stringify({
            query: request.query,
            body: request.body,
            params: request.params,
          }),
          result: JSON.stringify(data),
          ip: request.ip,
          userAgent: request.headers['user-agent'],
          duration: Date.now() - startTime,
        };

        await this.logService.create(logData);
      }),
    );
  }
}
